package com.master.chat.utils;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SqlProcessor {
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    //    自定义执行SQL
    public ResultSet query(String sql) throws SQLException {

        SqlSession sqlSession = openSession();
        PreparedStatement statement = sqlSession.getConnection().prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        closeSession(sqlSession);
        return resultSet;

    }


    public List<Map<String, Object>> queryList(String sql) {
        try {
            SqlSession sqlSession = openSession();
            PreparedStatement statement = sqlSession.getConnection().prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();

            List<Map<String, Object>> list = new ArrayList<>();

            while (resultSet.next()) {

                int colCnt = resultSet.getMetaData().getColumnCount();
                Map<String, Object> map = new HashMap<>();

                for (int i = 0; i < colCnt; i++) {
//                    System.out.println(resultSet.getMetaData().getColumnLabel(i) + resultSet.getString(i));
                    map.put(resultSet.getMetaData().getColumnLabel(i + 1), resultSet.getString(i + 1));
                }
                list.add(map);


            }

            return list;

        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }


    }

    //    开启链接
    private SqlSession openSession() {
        SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
        return sqlSessionFactory.openSession();
    }

    //    关闭链接
    private void closeSession(SqlSession sqlSession) {
        sqlSession.close();
    }
}

